package com.example.woke;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.woke.method.MyApp;
import com.zhongcai.online.R;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class BorrowforActivity extends Activity implements OnClickListener {

//	private Intent intent;
	private RadioGroup mGroup;
	private RadioButton mButton0,mButton1,mButton2,mButton3,mButton4,mButton5;
	private String fortype = "";
//	private ImageView mSend1,mSend2;
	private String feyanUsersId;
	private static final int PHOTO_CAPTURE = 0x11;
	private String photoPath = "/sdcard/zhongcai/";
	private boolean zorf = false;
	private String actionUrl = "http://zhongcai.iwoker.com:8384/index.php?g=api&m=quota&a=uploadfile";
	private String photoName = photoPath + "zhongcai.jpg";
	Uri imageUri = Uri.fromFile(new File(Environment
			.getExternalStorageDirectory(), "image.jpg"));
	private int dheight;
	private int dwidth;
//	private GridView mGridView;
	private String photo1 = "";//���3��ͼƬ
	private String photo2 = "";//���3��ͼƬ
	private String photo3 = "";//���3��ͼƬ
	private ArrayList<String> photolist = new ArrayList<String>();//ѡ��ͼƬ�ĵ�ַ
	private LayoutInflater minflater;
//	private Forwhyadter adapter;
	private MyApp myapp;
	private int jsld;//�ж����յĵڼ�����ť
	private ImageView mIadd1,mIadd2,mIadd3;
	private RelativeLayout mRelae1,mRelae2,mRelae3;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_borrowfor);
		
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads()
		.detectDiskWrites()
		.detectNetwork() 
		.penaltyLog()
		.build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		.detectLeakedSqlLiteObjects()
		.penaltyLog()
		.penaltyDeath()
		.build());
		myapp = (MyApp) getApplication();
		intview();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}
	
	private void intview() {
		minflater = getLayoutInflater();
		findViewById(R.id.avborrowfor_image_back).setOnClickListener(this);
		findViewById(R.id.avborrowfor_text_okback).setOnClickListener(this);
		mIadd1 = (ImageView) findViewById(R.id.avborrow_image_i1);
		mIadd2 = (ImageView) findViewById(R.id.avborrow_image_i2);
		mIadd3 = (ImageView) findViewById(R.id.avborrow_image_i3);
		
		mRelae1 = (RelativeLayout) findViewById(R.id.avborrow_for_r1);
		mRelae2 = (RelativeLayout) findViewById(R.id.avborrow_for_r2);
		mRelae3 = (RelativeLayout) findViewById(R.id.avborrow_for_r3);
		mRelae1.setOnClickListener(this);
		mRelae2.setOnClickListener(this);
		mRelae3.setOnClickListener(this);
		mGroup = (RadioGroup) findViewById(R.id.radioGroup1);
		mButton0 = (RadioButton) findViewById(R.id.radio0);
		mButton1 = (RadioButton) findViewById(R.id.radio1);
		mButton2 = (RadioButton) findViewById(R.id.radio2);
		mButton3= (RadioButton) findViewById(R.id.radio3);
		mButton4 = (RadioButton) findViewById(R.id.radio4);
		mButton5 = (RadioButton) findViewById(R.id.radio5);
		mGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				 if(checkedId==mButton0.getId()){
					 fortype = mButton0.getText().toString().trim();
					 }
				 if(checkedId==mButton1.getId()){
					 fortype = mButton1.getText().toString().trim();
					 }
				 if(checkedId==mButton2.getId()){
					 fortype = mButton2.getText().toString().trim();
					 }
				 if(checkedId==mButton3.getId()){
					 fortype = mButton3.getText().toString().trim();
					 }
				 if(checkedId==mButton4.getId()){
					 fortype = mButton4.getText().toString().trim();
					 }
				 if(checkedId==mButton5.getId()){
					 fortype = mButton5.getText().toString().trim();
					 }
			}
		});
	}
	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, final int parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(view, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					jsld = parent;
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					jsld = parent;
//					Intent intent = new Intent();  
//	                /* ����Pictures����Type�趨Ϊimage */  
//	                intent.setType("image/*");  
//	                /* ʹ��Intent.ACTION_GET_CONTENT���Action */  
//	                intent.setAction(Intent.ACTION_GET_CONTENT);   
//	                /* ȡ����Ƭ�󷵻ر����� */  
//	                startActivityForResult(intent, 1);
	                
	                Intent i = new Intent(
	   				Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
	   				startActivityForResult(i, 1);
	                
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == RESULT_OK && requestCode == 1) {  
			 Bitmap bm = null;
			 BitmapFactory.Options op = new BitmapFactory.Options();
				op.inSampleSize = 4; 
				ContentResolver resolver = getContentResolver();
					try {
						Uri originalUri = data.getData(); // ���ͼƬ��uri
						String[] proj = { MediaStore.Images.Media.DATA };
						Cursor cursor = managedQuery(originalUri, proj, null, null,
								null);
						// ���Ҹ������ ����ǻ���û�ѡ���ͼƬ������ֵ
						int column_index = cursor
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
						cursor.moveToFirst();
						// ���������ֵ��ȡͼƬ·��
						String path = cursor.getString(column_index);
						bm = BitmapFactory.decodeFile(path,op);
						if(jsld == 1){
							photo1 = ""+path;
							mIadd1.setImageBitmap(bm);
						}else if(jsld == 2){
							photo2 = ""+path;
							mIadd2.setImageBitmap(bm);
						}else{
							photo3 = ""+path;
							mIadd3.setImageBitmap(bm);
						}
					} catch (OutOfMemoryError e) {
					    //
						Toast.makeText(BorrowforActivity.this, "图片获取失败，请重试", Toast.LENGTH_SHORT).show();
					}
	        } 
		
		
		String sdStatus = Environment.getExternalStorageState();
		switch (requestCode) {
		case PHOTO_CAPTURE:
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			} else {
				BitmapFactory.Options op = new BitmapFactory.Options();
				op.inSampleSize = 4; 
				Bitmap bitmap = null;
				try {
				    // ʵ��Bitmap
				    bitmap = BitmapFactory.decodeFile(photoName,op);
				} catch (OutOfMemoryError e) {
				    //
					Toast.makeText(BorrowforActivity.this, "图片获取失败，请重试", Toast.LENGTH_SHORT).show();
				}
				
//				Bitmap bitMap = BitmapFactory.decodeFile(photoName,op);
				int width = bitmap.getWidth();
				int height = bitmap.getHeight();
				int newWidth = 480;
				int newHeight = 640;
				float scaleWidth = ((float) newWidth) / width;
				float scaleHeight = ((float) newHeight) / height;
				Matrix matrix = new Matrix();
				matrix.postScale(scaleWidth, scaleHeight);
				bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
						matrix, true);
//				Bitmap pic = null;
//				pic = BitmapFactory.decodeFile(photoName, op);
				Bitmap bitmap1 = null;
				switch (jsld) {
				case 1:
					if(!photo1.equals("")){
						try {
						    // ʵ��Bitmap
						    bitmap1 = BitmapFactory.decodeFile(photo1,op);
						    if(null != bitmap && !bitmap.isRecycled()){
						    	bitmap1.recycle();
						    	System.gc();
						    }
						} catch (OutOfMemoryError e) {
						    //
							Toast.makeText(BorrowforActivity.this, "图片获取失败，请重试", Toast.LENGTH_SHORT).show();
						}
					}
					if(null != bitmap){
						photo1 = photoName;
						mIadd1.setImageBitmap(bitmap);
					}
//					mRelae2.setBackgroundColor(getResources().getColor(R.color.usercenterbg));
//					mIadd1.setVisibility(View.VISIBLE);
//					photolist.remove(0);
//					photolist.add(0,photo1);
					break;
					
				case 2:
					if(!photo2.equals("")){
					try {
					    // ʵ��Bitmap
					    bitmap1 = BitmapFactory.decodeFile(photo2,op);
					    if(null != bitmap && !bitmap.isRecycled()){
					    	bitmap1.recycle();
					    	System.gc();
					    }
					} catch (OutOfMemoryError e) {
					    //
						Toast.makeText(BorrowforActivity.this, "图片获取失败，请重试", Toast.LENGTH_SHORT).show();
					}
					}
					if(null != bitmap){
						photo2 = photoName;
						mIadd2.setImageBitmap(bitmap);
					}
//					mRelae3.setBackgroundColor(getResources().getColor(R.color.usercenterbg));
//					mIadd3.setVisibility(View.VISIBLE);
//					photolist.remove(1);
//					photolist.add(1,photo2);
					break;
					
				case 3:
					if(!photo3.equals("")){
					try {
					    // ʵ��Bitmap
					    bitmap1 = BitmapFactory.decodeFile(photo3,op);
					    if(null != bitmap && !bitmap.isRecycled()){
					    	bitmap1.recycle();
					    	System.gc();
					    }
					} catch (OutOfMemoryError e) {
					    //
						Toast.makeText(BorrowforActivity.this, "图片获取失败，请重试", Toast.LENGTH_SHORT).show();
					}
					}
					if(null != bitmap){
						photo3 = photoName;
						mIadd3.setImageBitmap(bitmap);
					}
//					photolist.remove(2);
//					photolist.add(2,photo3);
					break;

				default:
					break;
				}
//				Log.e("photolist.size()", "***"+photolist.size());
//				if(photolist.size() < 3){
//					photolist.add("");
//				}
//				adapter.notifyDataSetChanged();
//				FileOutputStream b = null;
//				try {
//					b = new FileOutputStream(photoName);
//				} catch (FileNotFoundException e) {
//					e.printStackTrace();
//				}
//				if (pic != null) {
//					pic.compress(Bitmap.CompressFormat.JPEG, 50, b);
//				}
			}
			break;
		default:
			return;
		}
	}
	
	/* ��ʾDialog��method */
	private void showDialog(String mess) {
		new AlertDialog.Builder(BorrowforActivity.this).setTitle("��ʾ")
				.setMessage(mess)
				.setNegativeButton("ȷ��", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).show();
	}
	
	/* �ϴ��ļ���Server�ķ��� */
	private void uploadFile(String imageurldd) {
		System.out.print("正在发送请求！");
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		try {
			URL url = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* ����Input��Output����ʹ��Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* ���ô��͵�method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* ����DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"file1\";filename=\"" + "zhongcai.jpg" + "\"" + end);
			ds.writeBytes(end);
			/* ȡ���ļ���FileInputStream */
			FileInputStream fStream = new FileInputStream(imageurldd);
			/* ����ÿ��д��1024bytes */
			Log.e("已经找到数据正在发送！", "已经找到数据正在发送！");
			System.out.print("已经找到数据正在发送！");
			int bufferSize = 1024*10;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			/* ���ļ���ȡ����������� */
			while ((length = fStream.read(buffer)) != -1) {
				/* ������д��DataOutputStream�� */
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			/* close streams */
			fStream.close();
			ds.flush();
			/* ȡ��Response���� */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			/* ��Response��ʾ��Dialog */
			showDialog("上传成功");
			/* �ر�DataOutputStream */
			ds.close();
		} catch (Exception e) {
			System.out.print("网络出现异常！");
			showDialog("上传失败");
			e.printStackTrace();
		}
	}
	
	/**
	  * ����û������ʱ���ʾ��ʽ�����ص�ǰʱ��ĸ�ʽ �����yyyyMMdd��ע����ĸy���ܴ�д��
	  * 
	  * @param sformat
	  *            yyyyMMddhhmmss
	  * @return
	  */
	public static String getUserDate(String sformat) {
	  Date currentTime = new Date();
	  SimpleDateFormat formatter = new SimpleDateFormat(sformat);
	  String dateString = formatter.format(currentTime);
	  return dateString;
	}
	
	private void photo() {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		File file = new File(photoPath);
		if (!file.exists()) { 
			file.mkdir(); 
		}
		String stringDate = getUserDate("yyyyMMddhhmmss");
		photoName = photoPath + stringDate+".jpg";
		File photo = new File(photoName);
		imageUri = Uri.fromFile(photo);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
		startActivityForResult(intent, PHOTO_CAPTURE);
	}

	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.avborrowfor_image_back:
			finish();
			break;
			
		case R.id.avborrow_for_r1:
			new PopupWindows(BorrowforActivity.this,1);
			break;
			
		case R.id.avborrow_for_r2:
			new PopupWindows(BorrowforActivity.this,2);
			break;
			
		case R.id.avborrow_for_r3:
			new PopupWindows(BorrowforActivity.this,3);
			break;
			
		case R.id.avborrowfor_text_okback:
				if(!photo1.equals("")){
					photolist.add(photo1);
				}if(!photo2.equals("")){
					photolist.add(photo2);
				}if(!photo3.equals("")){
					photolist.add(photo3);
				}
				Intent intent = new Intent();
//				intent.setClass(BorrowforActivity.this,BorrowinfoActivity.class);
				intent.putExtra("fortype", fortype);
				intent.putExtra("photolist", photolist);
				setResult(302, intent);
				finish();
			break;

		default:
			break;
		}
	}

//	@Override
//	public void onItemClick(AdapterView<?> adapterview, View view, int i, long l) {
//		new PopupWindows(BorrowforActivity.this,i);
//	}

	
}
